package com.trkj.service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.trkj.dao.jpa.IDeilveryDetailDao;
import com.trkj.dao.jpa.IEquipDeliveryDao;
import com.trkj.dao.jpa.IEquipStroageSaveDao;
import com.trkj.pojos.DeilveryDetail;
import com.trkj.pojos.EquipDelivery;
import com.trkj.pojos.EquipStroageSave;

@Service
@Transactional
public class EquipDeliveryService {
	@Autowired
	private IEquipDeliveryDao deliveryDao;
	@Autowired
	private IDeilveryDetailDao deilveryDetailDao;
	@Autowired
	private IEquipStroageSaveDao equipStroageSaveDao;
	
	/**
	 * 生成出库ID
	 * @return
	 */
	public String creatDeliveryId(){
		String deliveryId = "";
		//将当前日期格式化为纯数字
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String str = sdf.format(new Date()).substring(2, 8);
		
		String LikeID = "%" + str + "%";
		List<String> list = deliveryDao.queryEquipDeliveryId(LikeID);

		if(list.isEmpty()){
			deliveryId = "CK" + str +"0001";
		}else{
			List<Integer> lists = new ArrayList<>();
			for(int i=0;i<list.size();i++){
				lists.add(Integer.valueOf(list.get(i).toString().substring(8, 12)));
			}
			//Collections.max取最大值再加1，拼接住院号
			 int next = Collections.max(lists).intValue()+1;
			 String nextID = String.format("%04d", next);
			 deliveryId = "CK" + str + nextID;
		}
		return deliveryId;
	}
	/**
	 * 保存出库单
	 * @param delivery
	 * @param deilveryDetail
	 * @param rdetailEquipsaveid
	 * @return
	 */
	public boolean deliverySave(EquipDelivery delivery, List<DeilveryDetail> deilveryDetail) {
		try {
			deliveryDao.save(delivery);
			String deliveryId=delivery.getDeliveryId();
			if(deilveryDetail!=null){
				for (DeilveryDetail detail : deilveryDetail) {
					detail.setDeliveryId(deliveryId);
					BigDecimal vdetailNum = detail.getVdetailNum();
					long vdetailEquipsaveid = detail.getVdetailEquipsaveid();
					
					EquipStroageSave findOne = equipStroageSaveDao.findOne(vdetailEquipsaveid);
					BigDecimal equipsaveNum = findOne.getEquipsaveNum();
					if(vdetailNum.equals(equipsaveNum)){
						equipStroageSaveDao.delete(findOne);
					}else{
						BigDecimal subtract = equipsaveNum.subtract(vdetailNum);
						findOne.setEquipsaveNum(subtract);
					}
				}
			}
			deilveryDetailDao.save(deilveryDetail);
			
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		
	}
}
